package ch.zbw.pra.sysventory.business.businessObject.scan;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.pra.sysventory.model.OperatingSystem;

/**
 * Gibt das Betriebssystem mittels WMI Schnittstelle auf einem bestimmten Host zurück
 * 
 * @author Ralph Koster
 */
public class ScanOperatingSystemBusinessObject implements Serializable {

	private static final long serialVersionUID = -2114205675265893326L;
	private static Logger LOG = LoggerFactory.getLogger(ScanOperatingSystemBusinessObject.class);
	
	private OperatingSystem operatingSystem;

	public ScanOperatingSystemBusinessObject() {

	}

	public OperatingSystem getOperatingSystemFromHost(String host) {

		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_OperatingSystem";
		try {

			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a java form.
				String operatingSystemName = Dispatch.call(item, "Caption").toString();
				String operatingSystemBuild = Dispatch.call(item, "Version").toString();
				String operatingSystemArchitecture = "NA";
				try {
					operatingSystemArchitecture = Dispatch.call(item, "OSArchitecture").toString();
				} catch (Exception e) {
					LOG.debug("Failed to load operating system on host" + host);
				}

				LOG.debug("Operating System found: " + operatingSystemName + " " + operatingSystemBuild + " "
						+ operatingSystemArchitecture);
				
				operatingSystem = new OperatingSystem(operatingSystemName, operatingSystemBuild,
						operatingSystemArchitecture);
			}
		} catch (Exception e) {
			LOG.debug("Failed to load operating system on host" + host);
			LOG.error(e.toString());
		}
		return operatingSystem;
	}
}
